/**
 * 模型相关工具函数
 */
import { settings } from '../core/settings.ts';

/**
 * 检查错误消息是否表示配额或计费问题
 * @param error 错误消息
 * @returns 是否为配额/计费问题
 */
export function isQuotaOrBillingError(error: string): boolean {
    const lowerError = error.toLowerCase();
    return (
        lowerError.includes('quota') ||
        lowerError.includes('exceed') ||
        lowerError.includes('billing') ||
        lowerError.includes('insufficient') ||
        lowerError.includes('balance') ||
        lowerError.includes('rate limit') ||
        lowerError.includes('exceeded')
    );
}

/**
 * 获取指定模型的API密钥
 * @param model 模型名称
 * @returns API密钥，未设置则返回undefined
 */
export async function getApiKeyForModel(model: string): Promise<string | undefined> {
    console.log(`尝试获取模型的API密钥: ${model}`);

    // 统一转换为小写进行比较
    const modelLower = model.toLowerCase();

    if (modelLower.includes('gpt')) {
        const apiKey = await settings.get('openai_api_key');
        console.log(`使用OpenAI API密钥: ${apiKey ? '已设置' : '未设置'}`);
        return apiKey;
    } else if (modelLower.includes('deepseek')) {
        const apiKey = await settings.get('deepseek_api_key');
        console.log(`使用DeepSeek API密钥: ${apiKey ? '已设置' : '未设置'}`);
        return apiKey;
    } else if (modelLower.includes('gemini')) {
        const apiKey = await settings.get('gemini_api_key');
        console.log(`使用Gemini API密钥: ${apiKey ? '已设置' : '未设置'}`);
        return apiKey;
    } else if (modelLower.includes('claude')) {
        const apiKey = await settings.get('anthropic_api_key');
        console.log(`使用Claude API密钥: ${apiKey ? '已设置' : '未设置'}`);
        return apiKey;
    } else if (
        modelLower.includes('glm') ||
        modelLower.includes('zhipu') ||
        modelLower.includes('yi') ||
        modelLower.includes('qwen') ||
        modelLower.includes('moonshot') ||
        modelLower.includes('baichuan')
    ) {
        const apiKey = await settings.get('siliconflow_api_key');
        console.log(`使用SiliconFlow API密钥: ${apiKey ? '已设置' : '未设置'}`);
        return apiKey;
    } else {
        // 找不到对应的API密钥
        console.log(`未知模型类型: ${model}`);
        return undefined;
    }
}

/**
 * 获取友好的人类可读错误消息
 * @param error 原始错误消息
 * @param model 使用的模型
 * @returns 友好的错误消息
 */
export function getHumanReadableError(error: string, model: string): string {
    console.log(`处理错误消息: ${error} (模型: ${model})`);

    const modelLower = model.toLowerCase();
    const providerName =
        modelLower.includes('gpt') ? 'OpenAI' :
            modelLower.includes('deepseek') ? 'DeepSeek' :
                modelLower.includes('gemini') ? 'Google Gemini' :
                    modelLower.includes('claude') ? 'Anthropic Claude' :
                        modelLower.includes('glm') || modelLower.includes('zhipu') ? '智谱GLM' :
                            modelLower.includes('yi') ? '零一万物Yi' :
                                modelLower.includes('qwen') ? '通义千问' :
                                    modelLower.includes('moonshot') ? 'Moonshot' :
                                        modelLower.includes('baichuan') ? '百川' :
                                            '所选AI服务';

    if (isQuotaOrBillingError(error)) {
        return `您的${providerName}账户已超出使用配额或存在计费问题。 可能的解决方法: 1. 检查您的账户余额 2. 更新付款信息 3. 升级您的账户套餐`;
    }

    if (error.toLowerCase().includes('api key')) {
        return `${providerName} API密钥无效。请在设置中检查并更新您的API密钥。`;
    }

    if (error.toLowerCase().includes('permission') || error.toLowerCase().includes('not authorized')) {
        return `您没有使用${providerName}所选模型的权限。请检查您的账户权限或选择其他模型。`;
    }

    if (error.toLowerCase().includes('未实现的命令')) {
        return `系统无法处理${providerName}的API请求。请检查应用配置或联系开发者。`;
    }

    return `${providerName}服务错误: ${error}`;
}

/**
 * 标准化模型名称
 * 将不同书写格式的模型名称统一为标准格式
 * 
 * @param model 模型名称
 * @returns 标准化后的模型名称
 */
export function standardizeModelName(model: string): string {
    if (!model) return '';

    console.log(`标准化模型名称: ${model}`);
    const modelLower = model.toLowerCase();

    // 标准化DeepSeek模型
    if (modelLower.includes('deepseek') && modelLower.includes('reasoner')) {
        return 'deepseek-reasoner';
    } else if (modelLower.includes('deepseek')) {
        return 'deepseek-chat';
    }

    // 标准化硅基流动模型
    else if (modelLower.includes('glm') || modelLower.includes('zhipu')) {
        return 'zhipu-glm-4';
    } else if (modelLower.includes('yi') || modelLower.includes('01-yi')) {
        return '01-yi-chat';
    } else if (modelLower.includes('qwen')) {
        return 'qwen-max';
    } else if (modelLower.includes('moonshot')) {
        return 'moonshot-v1-128k';
    } else if (modelLower.includes('baichuan')) {
        return 'baichuan-turbo';
    }

    // 默认返回原始模型名称
    return model;
}

/**
 * 获取提供商名称
 * @param model 模型名称
 * @returns 提供商名称
 */
export function getProviderForModel(model: string): string {
    const modelLower = model.toLowerCase();

    if (modelLower.includes('deepseek')) {
        return 'deepseek';
    } else if (
        modelLower.includes('glm') ||
        modelLower.includes('zhipu') ||
        modelLower.includes('yi') ||
        modelLower.includes('qwen') ||
        modelLower.includes('moonshot') ||
        modelLower.includes('baichuan')
    ) {
        return 'siliconflow';
    } else if (modelLower.includes('gpt')) {
        return 'openai';
    } else if (modelLower.includes('claude')) {
        return 'anthropic';
    } else if (modelLower.includes('gemini')) {
        return 'google';
    } else {
        return 'unknown';
    }
} 